<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="20">

            <!-- <a-col :md="5" :sm="24">
              <a-form-item label="业务员">
                <a-select
                  placeholder="请选择"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                >
                  <a-select-option :value="item.id" v-for="(item) in userList" :key="item.id">
                      {{item.username}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col> -->

            <a-col :md="6" :sm="24">
              <a-form-item label="供应商手机号">
                <a-input v-model="queryParam.mobile" placeholder="请输入供应商的手机号" />
              </a-form-item>
            </a-col>

            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons"
                :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd" v-action:addsupplierbtn2>新建</a-button>
      </div>

      <s-table ref="table" size="default" :rowKey="(record,index)=>{return index}" :columns="columns" :data="loadData"
        showPagination="auto">
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="imgurl" slot-scope="text, record">
          <a-avatar :src="record.imgurl" :size="54" />
        </span>
        <span slot="license" slot-scope="text, record">
          <a-avatar :src="record.license" :size="54" />
        </span>
        <!-- <span slot="username" slot-scope="text, record">
          <div>{{record.username}}</div>
          <div>{{record.password}}</div>
        </span> -->
        <span slot="yypic" slot-scope="text, record">
          <a-avatar :src="record.yypic" :size="54" />
        </span>
        <span slot="username" slot-scope="text, record">
          {{record.username}}
          <!-- <span style="text-decoration: underline;cursor:pointer" @click="showYWYList(record)">{{record.username}}</span> -->
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <!-- <a @click="open(record)">订单列表</a>
            <a-divider type="vertical" v-action:editsupplierbtn2 /> -->
            <a @click="handleEdit(record)" v-action:editsupplierbtn2>修改</a>
            <!-- <a-popconfirm v-action:deletesupplierbtn2 title="确定删除此供应商吗?" ok-text="确定" cancel-text="取消"
              @confirm="confirm(record)" @cancel="cancel(record)">
              <a @click="deleteSupplierBtn(record)">删除</a>
            </a-popconfirm> -->
            <a-divider type="vertical" v-action:deletesupplierbtn2 />
            <a v-action:deletesupplierbtn2 @click="deleteSupplierBtn(record)">删除</a>
          </template>
        </span>
      </s-table>

      <create-form ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :userList="userList"
        @cancel="handleCancel"
        @ok="handleOk"
        @getImage1="getImage1"
        @getImage2="getImage2"
      />
      <!-- <step-by-step-modal ref="modal" @ok="handleOk"/> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
  import {
    STable
  } from '@/components'

  import CreateForm from './modules/CreateForm'
  //引入供应商模块的接口
  import supplierApi from '@/api/supplier.js'
  import { getRoLeList, getUserList, AddUser, UpdateUser, DelUser } from '@/api/system'
 
  const columns = [{
      title: '编号',
      scopedSlots: {
        customRender: 'serial'
      }
    },
    {
      title: '门店照',
      align: 'center',
      scopedSlots: {
        customRender: 'imgurl'
      }
    },
    {
      title: '营业执照',
      dataIndex: 'license',
      scopedSlots: {
        customRender: 'license'
      }
    },
    {
      title: '营业时间',
      dataIndex: 'business_hours'
    },
    {
      title: '预约时间',
      dataIndex: 'appointment_hours'
    },
    {
      title: '联系人',
      dataIndex: 'contacts',
    },
    {
      title: '手机号',
      dataIndex: 'mobile'
    },
    {
      title: '地址',
      dataIndex: 'address'
    },
    {
      title: '绑定业务员',
      scopedSlots: {
        customRender: 'username'
      }
    },
    {
      title: '操作',
      dataIndex: '',
      width: '200px',
      scopedSlots: {
        customRender: 'action'
      }
    }
  ]
  const merchant = {
    'data': [{
      user_id: 3,
      name: '张三',
      lian: '里斯',
      avatar: '',
      mobile: 19142644397,
      area: '江西，南昌',
      startTime: '2016-05-11',
      yypic: '',
      cTime: '9.00 - 6.20',
      yTIme: '9.30 - 4.00'
    }, ],
    'pageSize': 10,
    'pageNo': 1,
    'totalPage': 6,
    'totalCount': 2
  }

  export default {
    name: 'yzusupplier',
    components: {
      STable,
      CreateForm,
    },
    data() {

      this.columns = columns
      return {
        value: '',
        username: '',
        imgurl: '', //门店照
        license: '', //营业执照
        salesmanList: [{
          key: 1,
          label: '业务员1'
        }, {
          key: 2,
          label: '业务员2'
        }, {
          key: 3,
          label: '业务员3'
        }],
        visibles: false,
        // create model
        visible: false,
        confirmLoading: false,
        mdl: null,
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {
          // username:'',
          // mobile:''
        },
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          const requestParameters = Object.assign({}, parameter, this.queryParam)
          // console.log('loadData request parameters:', requestParameters)
          // return new Promise((res, rej) => {
          //   res()
          // }).then(res => {
          //   return merchant
          // })
          return supplierApi.SupplierPage(requestParameters)
            .then(res => {
              return res.data
            })
        },
        selectedRowKeys: [],
        selectedRows: [],
        userList: [],
        sale_id: '',
        role_id: '',
        gys_user_id:''
      }
    },
    created() {
      this.getRoleList()
      // this.getUserList()
    },
    computed: {
      rowSelection() {
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      }
    },
    mounted() {
      console.log("api.upload", this.$api.upload)
      
    },
    methods: {
      onSelect(value) {
        console.log('onSelect', value);
      },
      onSearch(value) {
        // this.getUserList()
        // this.userList = !value ? [] : [value, value.repeat(2), value.repeat(3)]
        this.userList = this.getUserListByUserName(value)
        console.log('this.userList', this.userList)
        this.$forceUpdate()
      },
      onChange(value) {
        console.log('onChange', value);
      },
      getRoleList() {
        getRoLeList().then(res => {
          const list = res.data.data
          list.forEach(item => {
            if (item.name == '业务员') {
              this.getUserListByRoleId(item.id)
            }
            if(item.name == '供应商') {
              this.role_id = item.id // 获取供应商role_id
            }
          })
        })
      },
      getUserListByRoleId(role_id) {
        const params = {
          role_id
        }
        getUserList(params).then(res => {
          this.userList = res.data.data
        })
      },
      async getUserListByUserName(username) {
        const params = {
          username
        }
        await getUserList(params).then(res => {
          return res.data.data
        })
      },
      async getUserListByMobile(mobile) {
        const params = {
          mobile
        }
        await getUserList(params).then(res => {
          const itemUser = res.data.data
          //this.role_id为供应商的角色ID
          this.gys_user_id = itemUser.filter(item=>item.role_id==this.role_id)[0].id
          console.log('this.gys_user_id',this.gys_user_id)
        })
      },
      getUserList() {
        const params = {
          pageNo: 1,
          pageSize: 1000
        }
        getUserList(params).then(res => {
          this.userList = res.data.data
        })
      },
      getImage1(val) {
        this.imgurl = val
        console.log('getImage1', val)
      },
      getImage2(val) {
        this.license = val
        console.log('getImage2', val)
      },
      handleChange3Salesman(val) {
        console.log("val", val)
        console.log("this.queryParam.salesman", this.queryParam.salesman)
        // this.queryParam.salesman = this.salesmanList[this.$route.query.user_id-1].label
      },
      showYWYList(record) {
        //alert('待开发')
        this.$router.push({
          path: `/yzusupplier/supplier/supplierinfo`,
          query: {
            key: record.user_id,
            name: record.name
          }
        })
      },
      // 查看详情
      open(e) {
        this.item = e
        console.log('------------------', e)
        // this.visibles = true
        this.$router.push('/yzuorder/orderList/index')
      },
      // 搜素模糊查询
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      },
      handleAdd() {
        this.mdl = null
        this.visible = true
      },
      handleEdit(record) {
        this.getUserListByMobile(record.mobile)
        this.visible = true
        console.log('this.visible',this.visible)
        this.mdl = {
          ...record
        }
      },
      // 创建
      handleOk() {
        const form = this.$refs.createModal.form
        this.confirmLoading = true
        form.validateFields((errors, values) => {
          if (!errors) {
            values.imgurl = this.imgurl
            values.license = this.license
            console.log('+++values+++', values)
            if(values.id>0){ //修改
              const params = {
                id:this.gys_user_id,// 该供应商在用户表中所对应的用户ID，点击编辑的时候会通过手机号来获取
                nickname:values.contacts,
                mobile:values.mobile,
              }
              UpdateUser(params).then(res => {
                 
              })
            }else{ //添加
              // const params = {
              //   username:values.username,
              //   nickname:values.contacts,
              //   password:values.password,
              //   mobile:values.mobile,
              //   role_id: this.role_id,
              // }
              // // 往用户表中加数据
              // AddUser(params).then(res => {
                 
              // })
            }
            // 往供应商表中加数据
            new Promise((resolve, reject) => {
              // delete values.username
              // delete values.password
              supplierApi.SupplierSave(values).then(value => {
                if (value) {
                  resolve()
                } else {
                  this.confirmLoading = false
                }
              })
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success(values.id > 0 ? '修改成功' : '新增成功')
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      deleteSupplierBtn(record) {
        const _this = this
        this.getUserListByMobile(record.mobile).then(res=>{
          console.log('deleteSupplierBtn',res)
          this.$confirm({
            title: '系统提示',
            content: '确定删除这个供应商吗?',
            onOk () {
              _this.confirm(record)
            },
            onCancel () {}
          })
        })
        
      },
      // 删除
      confirm(e) {
        const form = this.$refs.createModal.form
        DelUser({id: this.gys_user_id}).then(res => {
          
        })
        supplierApi.SupplierDel({
          id: e.id
        }).then(res => {
          if (res.ret == 200) {
            // 重置表单数据
            form.resetFields()
            // 刷新表格
            this.$refs.table.refresh()
            this.$message.success('删除成功');
          }
        }).catch(error => {
          console.log('-------------error------------', error)
        })
      },
      cancel(e) {
        console.log(e);
        this.$message.error('已取消');
      },
      handleCancel() {
        this.visible = false

        const form = this.$refs.createModal.form
        form.resetFields() // 清理表单数据（可不做）
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      toggleAdvanced() {
        this.advanced = !this.advanced
      },
      // 重置
      reset() {
        const form = this.$refs.createModal.form
        this.queryParam = {}
        // 重置表单数据
        form.resetFields()
        // 刷新表格
        this.$refs.table.refresh()
      },
    },
  }
</script>
<style scoped>
  /* 文字溢出隐藏并显示省略号 */
  .textfont {
    width: 200px;
    height: 40px;
    /* height: 100%; */
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    /* 设置行数 */
    -webkit-box-orient: vertical;
  }
</style>
